package com.anrongtec.zcpt.openapi.manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.HandlerThread;

import com.anrongtec.zcpt.openapi.interfaces.HttpUtil;
import com.anrongtec.zcpt.openapi.util.Util;

import java.lang.ref.WeakReference;

/**
 * 统一认证管理类
 * 
 * @author dongtianhao
 *
 */
public class UAManager {
	private static final String MDM_PKG_NAME = "com.ansec.mdm";
	private static final String THREAD_NAME = "ua_handler_name";
	private static final String LOGIN_THREAD_NAME = "ua_handler_login_name";
	private static final String LOGOUT_THREAD_NAME = "ua_handler_logout_name";
	private static final String REFRESH_THREAD_NAME = "ua_handler_refresh_name";
	private volatile static UAManager mInstance;
	// 同步锁
	private static Object INSTANCE_LOCK = new Object();
	private Context context;
	// 是否绑定了MDM的服务
	private String appKey;
	private String accessToken;
	private HandlerThread mThread;
	private UAHandler mHandler;

	/**
	 * 使用单例模式创建--双重锁定
	 */
	public static UAManager getInstance() {
		if (mInstance == null) {
			synchronized (INSTANCE_LOCK) {
				if (mInstance == null) {
					mInstance = new UAManager();
				}
			}
		}
		return mInstance;
	}

	private UAManager() {

	}

	public void init(Context context, String appKey) {
		this.context = context;
		this.appKey = appKey;
	}

	private WeakReference<Activity> weakReference;

	public void authLogin(final Activity activity, String mPackageName, final IAuthCallBack authCallBack) {
		if (activity == null) {
			throw new NullPointerException("activity 不可为空");
		}
		if (authCallBack == null) {
			throw new NullPointerException("IAuthCallBack 回调接口不可为空");
		}
		weakReference = new WeakReference<Activity>(activity);
		mThread = new HandlerThread(LOGIN_THREAD_NAME);
		mThread.start();
		mHandler = new UAHandler(mThread.getLooper());
		mHandler.init(context, appKey);
		// 先查看是否具备统一认证权限。向服务器请求是否具备认证权限，pkg、sha1、AK，返回应用授权。access_token
		mHandler.authLogin(authCallBack,mPackageName, weakReference);
	}

	/**
	 * 切换用户
	 * 
	 * @param
	 * @param authCallBack
	 */
	public void switchLogin(final String accessToken, String pkgName ,final Activity activity, final IAuthCallBack authCallBack) {
		if (authCallBack == null) {
			throw new NullPointerException("IAuthCallBack 回调接口不可为空");
		}
		mThread = new HandlerThread(LOGIN_THREAD_NAME);
		mThread.start();
		mHandler = new UAHandler(mThread.getLooper());
		mHandler.init(context, appKey);
		mHandler.switchLogin(accessToken, pkgName,activity, authCallBack);
	}

	/**
	 * 登出
	 * 
	 * @param accessToken
	 * @return
	 */
	public boolean authLogout(String accessToken) {
		if (context == null) {
			throw new NullPointerException("SDK尚未初始化");
		}
		if (!Util.isAppInstalled(context.getApplicationContext(), MDM_PKG_NAME)) {
			return false;
		}
		context.sendBroadcast(new Intent("com.ansec.mdm.action.logout"));
		return true;
	}

	/**
	 * 登出,被切换用户代替
	 */
	private void authLogout(String accessToken, Activity activity, IAuthCallBack authCallBack) {
		if (context == null) {
			throw new NullPointerException("SDK尚未初始化");
		}
		if (!Util.isAppInstalled(context.getApplicationContext(), MDM_PKG_NAME)) {
			authCallBack.onError(996, "终端安全管控未安装，请先安装终端安全管控");
		}
		mThread = new HandlerThread(LOGOUT_THREAD_NAME);
		mThread.start();
		mHandler = new UAHandler(mThread.getLooper());
		mHandler.init(context, appKey);
		WeakReference<Activity> weakReference = new WeakReference<Activity>(activity);
		mHandler.setCurrentActivity(weakReference);
		mHandler.setAuthCallBack(authCallBack);
		// 清空终端安全管控人员信息
		Intent intent = new Intent("com.ansec.mdm.action.login");
		intent.putExtra("is_logout", true);
		activity.startActivityForResult(intent, 100);
	}

	/**
	 * 刷新Token
	 */
	public void refreshToken(final String accessToken, final OperationCallBack callback) {
		if (callback == null) {
			throw new NullPointerException("回调接口不可为空");
		}
		HandlerThread mThread = new HandlerThread(REFRESH_THREAD_NAME);
		mThread.start();
		UAHandler mHandler = new UAHandler(mThread.getLooper());
		mHandler.init(context, appKey);
		mHandler.refreshToken(accessToken, callback);
	}

	/**
	 * 处理返回结果
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 */
	public void decodeResult(int requestCode, int resultCode, Intent data) {
		mHandler.decodeResult(requestCode, resultCode, data);
	}

	/**
	 * 获取用户信息
	 * 
	 * @return
	 */
	public void getStaffInfo(final String accessToken, final OperationCallBack callBack) {
		mThread = new HandlerThread(LOGIN_THREAD_NAME);
		mThread.start();
		mHandler = new UAHandler(mThread.getLooper());
		mHandler.init(context, appKey);
		mHandler.getStaffInfo(accessToken, callBack);
	}

	/**
	 * 取消所有统一认证的请求
	 */
	public void cancelAuth() {
		HttpUtil.cancelAuth();
	}
}
